// const button = document.querySelector('button#test');

let pasteUrl = "";

// let debugStyle = 
//     // ""
//     "text:black;"
//     ;

async function paste() {
  let text = await navigator.clipboard.readText();
  // alert(text);
  console.log("clipboard:", text);
  let tip = document.createElement("div");
  //tip.innerText=`Clipboard: ${text}`;
  tip.innerHTML=`<div class='debugTxt'>Clipboard:<br/> ${text}</div>`;
  document.body.appendChild(tip);

//   if(!text.startsWith("http")){
  if(!text.startsWith("https://api.bilibili.com/x/player/videoshot")){
    return;
  }

  pasteUrl = text;

    // let url = "https://api.bilibili.com/x/player/videoshot?aid=113259545891941&cid=26166562321";
    let url = text;

    fetch(url, {
        // https://stackoverflow.com/questions/42239643/when-do-browsers-send-the-origin-header-when-do-browsers-set-the-origin-to-null
        mode: 'no-cors',
    })
        .then((response) => response.json())
        //   .then((json) => console.log(json))
        .then((json) => handleVideoshotJson(json))
        ;

}

        let img_x_len = 0;
        let img_y_len = 0;
        let width, height = 0;
        let images = "";
        let pvdataUrl = "";

    function handleVideoshotJson(json) {
        console.log("json", json);
        img_x_len = json.data.img_x_len;
        img_y_len = json.data.img_y_len;
        width = json.data.img_x_size;
        height = json.data.img_y_size;
        images = json.data.image;
        pvdataUrl = json.data.pvdata;
        // console.log("img_x_len", img_x_len);
        console.log("w", width, "h", height);
        // console.log("images", images);
        // images.forEach(img => {
        //     console.log(img);
        // });

        getpvdata();

        // TODO show after getting all data

    }

    function genUI(){
        var r = document.querySelector(':root');
        r.style.setProperty('--width', width);
        r.style.setProperty('--height', height);

        // let rs=getComputedStyle(r);
        // // console.log("getComputedStyle", rs);
        // let w = rs.getPropertyValue("--width");
        // console.log("comp w", w, "h", rs.getPropertyValue("--height"));

        // TODO debug
        // images[0]="//bimp.hdslb.com/videoshotpvhdboss/26293895878_89i4yb-0031.jpg1";
        // images[2]="//bimp.hdslb.com/videoshotpvhdboss/26293895878_89i4yb-0031.jpg1";
        
        /*
        update: seems for very long videos, e.g. https://www.bilibili.com/video/BV1xoXpYmEVz/ , server will return all images (18)
        xxx: when shot images are more then 10, server only returns 10. so we try the best to get them all.

        if an image doesn't exist, simply let the javascript itself's error break the program
        */
        console.log("images", images.length);
       if(images.length==9){
        let first = images[0];
           for (let i = 10; i < 50; i++) {
               let rep = first.replace("-0001.jpg", `-00${i}.jpg`);
               images.push(rep);
           }
           console.log("images", images.length);
       }

        genGrids();
    }


    function genGrids() {

        let pvIdx = 2;
        let subtitleIdx = 0;

        for (let i = 0; i < images.length; i++) {

            imgSrc="https:"+images[i];

            let elm = document.createElement("div");
            elm.innerText = imgSrc;
            elm.className = "debugTxt";
            document.body.appendChild(elm);


            for (let y = 0; y < img_y_len; y++) {
                for (let x = 0; x < img_x_len; x++) {
                    let elm = document.createElement("div");
                    elm.className = "wrap";
                    // elm.style=`width:${width}px; height:${height}px; overflow: hidden; display: inline-block;`;

                    elm.innerHTML = `<img style="margin: -${y * height}px 0px 0px -${x * width}px" src='${imgSrc}'></img>`;
                    document.body.appendChild(elm);


                    if(subtitles.length==0){
                        continue;
                    }

                    // add sub content
                    if(pvTimes.length > pvIdx){
                        let nextStartTime = pvTimes[pvIdx];

                        console.log("pvIdx", pvIdx, "nextFrom", nextStartTime);

                        let imgSub = "";

                        for(;;){
                            let sub = subtitles[subtitleIdx];
                            if(!sub){
                                break;
                            }

                            if(sub.from < nextStartTime){
                                console.log("add sub", sub);

                                // display min:sec
                                let min = ~~(sub.from / 60);
                                let sec = ~~(sub.from % 60);

                                imgSub += min +":"+ sec + " " + sub.content + "<br/>\n";
                                ++subtitleIdx;
                            }else{
                                break;
                            }
                        }
                        console.log("imgSub", imgSub);

                        elm = document.createElement("div");
                        elm.className = "wrap";
                        elm.innerHTML = `<div>${imgSub}</div>`;
                        document.body.appendChild(elm);
                    }

                    ++pvIdx;
                }
            }
        }
    }


    function getpvdata(){
        // console.log("get pv data");
      let url = "https:"+pvdataUrl;
  
      fetch(url, {
          // https://stackoverflow.com/questions/42239643/when-do-browsers-send-the-origin-header-when-do-browsers-set-the-origin-to-null
          mode: 'no-cors',
      })
          //   .then((json) => console.log(json))
          .then((resp) => resp.arrayBuffer())
          .then((resp) => handlePVData(resp))
          ;
    }

    let pvTimes = [];

      function handlePVData(json) {
        //   console.log("pvdata", json);

        let dv = new DataView(json);
        console.log("dv byte len", dv.byteLength);
        const BYTES=2;
        // console.log("dv",dv);
        for(let i=0;i<dv.byteLength/BYTES;i++){
            let ui = dv.getUint16(i*BYTES, false);
            // console.log(i, "ui", ui);
            pvTimes.push(ui);
        }

        getSubtitle();
      }

      function getSubtitle(){
      let url = 
    //   "https://api.bilibili.com/x/player/wbi/v2?aid=872819895&cid=1250535565"
    pasteUrl.replace("videoshot", "wbi/v2")
    ;

    // pasteUrl = "https://api.bilibili.com/x/player/videoshot?aid=113259545891941&cid=26166562321";
  
      fetch(url, {
          // https://stackoverflow.com/questions/42239643/when-do-browsers-send-the-origin-header-when-do-browsers-set-the-origin-to-null
          mode: 'no-cors',

        //   credentials: 'include',
      })
          .then((response) => response.json())
          //   .then((json) => console.log(json))
          .then((resp) => checkSubtitle(resp))
          ;
      }

  let subUrl = "";

      function checkSubtitle(json) {
        //   console.log("json", json);
          let sbs = json.data.subtitle.subtitles;
          console.log("sbs", sbs);

          if(sbs.length>0){
            // has subtitle
            subUrl = "https:"+sbs[0].subtitle_url;
            console.log("subUrl", subUrl);

            // get subtitle
            fetch(subUrl, {
                mode: 'no-cors',
            })
            .then(resp => resp.json())
            .then(resp => handleSubtitle(resp))
            ;
          }else{
            // no subtitle
            genUI();
          }
      }

      let subtitles = [];

      function handleSubtitle(json) {
        //   console.log("sub", json);
          subtitles = json.body;
          console.log("got sbs", subtitles);
          console.log("got sbs len", subtitles.length);
      
        genUI();
      }


// button.addEventListener('click', paste);

window.onload = paste;
// window.onload = setTimeout(paste, 1000);
